<template>
  <div class="grid-view" ref="gridView">
    <slot></slot>
  </div>
</template>

<script>
  export default {
    name: "GridView",
    data() {
      return {
        clientWidth: this.gridViewWidth
      }
    },
    props: {
      cols: {
        type: Number,
        default: 2,
      },
      hMargin: {
        type: Number,
        default: 8,
      },
      vMargin: {
        type: Number,
        default: 8,
      },
      itemSpace: {
        type: Number,
        default: 8,
      },
      lineSpace: {
        type: Number,
        default: 8,
      },
      gridViewWidth: {
        type: Number,
        default: 0,
      }
    },
    mounted() {
      setTimeout(this.autoLayout, 20);
    },
    updated() {
      this.autoLayout();
    },
    methods: {
      autoLayout() {
        // 1. 获取 gridEl children
        let gridEl = this.$refs.gridView;
        let children = gridEl.children;

        // 2. 设置 gridEl 的宽度
        this.clientWidth = this.clientWidth || gridEl.clientWidth;

        // 3. 设置 gridEl 的内边距 vertical horizontal
        gridEl.style.padding = `${this.vMargin}px ${this.hMargin}px`;

        // 4. 计算 item 的高度
        let itemWidth = (this.clientWidth
                        - 2 * this.hMargin
                        - (this.cols - 1) * this.itemSpace)
                        / this.cols - 5;

        // 5. 将 children 伪数组转为真数组
        for (let [index, item] of Array.prototype.slice.call(children).entries()) {
          item.style.width = itemWidth + 'px';

          // 不是一行的最后一个
          if ((index + 1) % this.cols !== 0) {
            item.style.marginRight = this.itemSpace + 'px';
          }

          // 一行结束换下一行的时候距离顶部的距离
          if (index >= this.cols) {
            item.style.marginTop = this.lineSpace + 'px';
          }
        }
      }
    },

    watch: {
      clientWidth() {
        this.clientWidth = this.$refs.gridView.clientWidth;
      }
    }
  }
</script>

<style scoped>
  .grid-view {
    display: flex;
    flex-wrap: wrap;
  }
</style>
